"""
计算两日期相隔天数
"""

from datetime import datetime
import time


def date2int(d, delim='-'):
    """字符日期转数字, 为比较日期前后作准备, 注意前置 0"""
    y, m, d = d.split(delim)
    m = '%02d' % int(m)
    d = '%02d' % int(d)
    return int(''.join((y, m, d)))


def is_leep(year):
    # ref: https://stackoverflow.com/a/48747097/4154610
    return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)


def year_days(year):
    return 366 if is_leep(year) else 365


def days_of_year(y, m, d):
    days_of_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    days_of_month[1] = 29 if is_leep(y) else 28
    days = sum(days_of_month[:m - 1]) + d
    return days


def diff_days(date1, date2, date_delim='-'):
    # 测试日期大小, 保证 date1 < date2
    if date2int(date1) > date2int(date2):
        date1, date2 = date2, date1
    tot_days = 0
    y1, m1, d1 = list(map(int, date1.split(date_delim)))
    y2, m2, d2 = list(map(int, date2.split(date_delim)))
    if y1 == y2:
        tot_days = days_of_year(y2, m2, d2) - days_of_year(y1, m1, d1)
    else:
        tot_days = year_days(y1) - days_of_year(y1, m1, d1) + days_of_year(
            y2, m2, d2) + sum([year_days(y) for y in range(y1 + 1, y2)])
    return tot_days


def diff_days_datetime(d1, d2):
    # ref: https://stackoverflow.com/a/8419655/4154610
    d1 = datetime.strptime(d1, "%Y-%m-%d")
    d2 = datetime.strptime(d2, "%Y-%m-%d")
    return abs((d2 - d1).days)


def diff_days_time(date1, date2):
    # 有局限性, 不能计算大年份
    d1 = time.mktime(time.strptime(date1, '%Y-%m-%d'))
    d2 = time.mktime(time.strptime(date2, '%Y-%m-%d'))
    s = int(abs(d2 - d1) / 3600 / 24)
    return s


if __name__ == "__main__":
    test_dates_pairs = [
        ['2017-4-7', '2016-04-09'],
        ['2008-8-08', '2019-04-01'],
        ['2040-09-10', '2080-12-31'],
        ['2018-09-10', '2018-12-31'],
        ['2010-09-10', '3100-12-31'],
    ]
    for t in test_dates_pairs:
        print(diff_days(*t))
        print(diff_days_datetime(*t))
        print(diff_days_time(*t))
        print('-' * 13)
